import React, { createRef, PureComponent } from 'react'
import { history } from '@umijs/max'
import {
 InputSearch, ProTable, ProTableOperate, ProTableOptions,
} from '@/components'
import styles from './index.less'

const { OperateItem } = ProTableOperate

export default class SafetyManagement extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      columns: [
        {
          title: 'API名称',
          dataIndex: 'apiName',
          width: '25%',
          key: 'apiName',
          // ellipsis: true,
        },
        {
          title: 'API描述',
          dataIndex: 'apiDesc',
          width: '25%',
          key: 'apiDesc',
          // ellipsis: true,
          render: (apiDesc) => (apiDesc || '-'),
        },
        {
          title: '授权用户数',
          dataIndex: 'userNumber',
          width: '20%',
          key: 'userNumber',
          // ellipsis: true,
          render: (username) => (username || '-'),
        },
        {
          title: '累计调用总数',
          dataIndex: 'totalCount',
          width: '15%',
          key: 'totalCount',
          // ellipsis: true,
          render: (totalCount) => (totalCount || '-'),
        },
        {
          title: '操作',
          key: 'action',
          render: (record) => {
            const {
              id, userNumber,
            } = record
            return (
              <ProTableOptions>
                {
                  (userNumber > 0 || null) && (<span onClick={() => { history.push(`/data-service/safety-management-edit?id=${id}`) }}>编辑授权</span>)
                }
              </ProTableOptions>
            )
          },
        },
      ],
      apiName: '',
    }
    this.tableRef = createRef()
  }

  fetchData = () => {
    const { apiName, query } = this.state
    this.tableRef?.current?.resetPageNum()
    const tempQuery = {}
    tempQuery.apiName = apiName
    this.setState({
      query: {
        ...query,
        ...tempQuery,
      },
    })
  }

  render() {
    const {
      columns, loading, query, forceUpdate,
    } = this.state
    return (
      <div className={styles.safety_management}>
        <ProTableOperate style={{ marginTop: 0 }}>
          <OperateItem align="left">
            <InputSearch
              placeholder="请输入API名称进行搜索"
              onChange={(e) => {
                this.setState({
                  apiName: e.target.value,
                })
              }}
              onSearch={this.fetchData}
            />
          </OperateItem>
        </ProTableOperate>
        <ProTable
          ref={this.tableRef}
          loading={loading}
          key={forceUpdate}
          url="/api/v1/dataApiSecurityManage/getApiSecurityManagePage"
          query={query}
          rowKey="id" // key传递的是否有效，影响rowSelection的使用
          columns={columns}
        />
      </div>
    )
  }
}
